import { del_status, getKnowledgeList, set_status } from "@/api/knowledge";
import { ActionType, ProCard, ProTable } from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Affix, Breadcrumb, Card, Form, Image, Input, Row, Select, Col, Button, Tooltip, Popconfirm, message, Drawer, Space, Switch } from "antd";
import know from './knowledge.less'
import { ReactNode, useRef, useState } from "react";
import { NavLink } from "umi";
import Meta from 'antd/lib/card/Meta';

import { CloseOutlined, CloudDownloadOutlined, CloudUploadOutlined, DeleteOutlined, EditOutlined, InboxOutlined, SettingOutlined, ZoomOutOutlined } from "@ant-design/icons";
import TextArea from "antd/lib/input/TextArea";
import Dragger from "antd/lib/upload/Dragger";
type GithubIssueItem = {
  cover: string;
  id: string;
  number: number;
  title: string;
  summary: string;
  comments: number;
  status: string;
  updated_at: string;
  closed_at?: string;
  url: string;
  originalname: string;
};


export default function Knowledge() {

  const { Option } = Select;
  const user = JSON.parse(localStorage.getItem('userinfo')!);
  // true 为编辑 false 为新增
  const [flag, setFlag] = useState(false)
  const [visible , setVisible] = useState(false)
  const [visible2 , setVisible2] =useState(false)
  const [switchValue,setswitchValue] = useState(false)
  const { runAsync } = useRequest<any, any>(getKnowledgeList, {
    manual: true
  })
  const onClose =()=>{
    setVisible(false)
  }

  //获取表格的组件实例
  const actionRef = useRef<ActionType>()


  //显示编辑卡片
  const showDrawerEdit = (item: GithubIssueItem) => {
    if (user.role === 'visitor') {
      message.warning('访客无权进行该操作');
    } else {
      setFlag(true)
      //formRef.current.setFieldsValue(item);
      setVisible(true)
    }
  }
  const showDrawer2 = () => {
    setVisible2(true);
  };
  //编辑
  const onFinishEdit=()=>{

  
  }
  //新增
  const onFinish=()=>{

  }
  const columns = [
    {
      dataIndex: 'title',
      ellipsis: true,
      render: (text: ReactNode, record: any, index: number) => {
        return <Card
          // 卡片封面
          cover={
            <Image
              style={{ width: '100%', height: 120 }}
              alt={record.title}
              src={record.cover} />
          }

          /* 卡片底部 */
          actions={[
            //编辑按钮
            <EditOutlined key='edit'>

            </EditOutlined>,//发布线上按钮
            record.status === 'draft' ? (
              //tooltip文字提醒
              <Tooltip
                title={'发布线上'}
                // @ts-ignore
                onClick={() => {


                  if (user.role === 'visitor') {
                    message.warning('访客无权进行该操作');
                  } else {
                    record.status = 'publish';
                    set_status(record.id, record.status);
                    init();
                  }
                }}
              >
                <CloudUploadOutlined />
              </Tooltip>
            ) : (
              <Tooltip
                title={'设为草稿'}
                // @ts-ignore
                onClick={() => {



                  if (user.role === 'visitor') {
                    message.warning('访客无权进行该操作');
                  } else {
                    record.status = 'draft';
                    set_status(record.id, record.status);
                    init();
                  }
                }}
              >
                <CloudDownloadOutlined />
              </Tooltip>
            ), <SettingOutlined
              key='setting'
              onClick={() => {
                showDrawerEdit(record)
              }}
            >

            </SettingOutlined>,
            <Popconfirm title='确定删除这个评论？'
              okText="确认"
              cancelText="取消"
              onConfirm={() => {
                if (user.role === 'visitor') {
                  message.warning('访客无权进行该操作');
                } else {
                  del_status(record.id);
                  message.success('删除成功');
                  init();
                }
              }}
            >
              <DeleteOutlined />
            </Popconfirm>
          ]}
        >
          <Meta title={record.title} description={record.summary} />
        </Card>
      }
    }
  ]
  //刷新页面
  const init = () => {


    actionRef.current && actionRef.current.reload();
  }

  return (
    <div className={know.knowledge}>
      <Affix offsetTop={top}>
        <ProCard >
          <Breadcrumb>
            <Breadcrumb.Item><NavLink to='/home'>工作台</NavLink></Breadcrumb.Item>
            <Breadcrumb.Item>知识小册 </Breadcrumb.Item>
          </Breadcrumb>
        </ProCard>
      </Affix>
      <Form style={{
        margin: '30px 0',
        background: '#fff',
        display: 'flex',
        alignItems: "center",
        justifyContent: "space-between",

      }}>
        <Row>
          <Form.Item label="名称" name="title">
            <Input
              placeholder="请输入名称"
              style={{ width: 150, marginRight: 10 }}
            />
          </Form.Item>
          <Form.Item label="状态" name="status">
            <Select style={{ width: 150 }} >
              <Option value="publish">已发布</Option>
              <Option value="draft">草稿</Option>
            </Select>
          </Form.Item>
        </Row>
        <Row>
          {/* <Col>
          </Col> */}
          <Button>搜索</Button>
          <Button onClick={() => init()}>重置</Button>
        </Row>
      </Form>
      {/* 新增和编辑 */}
      <Drawer 
      width={600}
      title={flag?'编辑知识库':'新建知识库'}
      visible={visible}
      forceRender={true}//预渲染
      placement="right"
      closable={false}//关闭按钮
      onClose={onClose}
      extra={//编辑页面的关闭按钮
        <Space>
          <CloseOutlined key="clone" onClick={onClose} />
        </Space>
      }//页脚
      footer={[
        <Button style={{ margin: '0 8px' }} key="back" onClick={onClose}>
        返 回
      </Button>,
      // @ts-ignore
      flag ? (
        <Button key="go" type="primary" onClick={onFinishEdit}>
          编 辑
        </Button>
      ) : (
        <Button key="go" type="primary" onClick={onFinish}>
          新 增
        </Button>
      ),
      ]}
      footerStyle={{display:"flex",justifyContent:"flex-end"}}
      >
        <Form 
        name="control-hooks"
        >
          <Form.Item name="title" label="名称" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="summary" label="描述" rules={[{ required: true }]}>
            <TextArea style={{ height: 100 }} />
          </Form.Item>
          <Form.Item
            name="isCommentable"
            label="评论"
            rules={[{ required: true }]}
          >
            <Switch
              checked={switchValue}
              onChange={() => {
                setswitchValue(!switchValue);
              }}
            />
          </Form.Item>
          <Form.Item name="img" label="封面" rules={[{ required: true }]}>
            <Dragger showUploadList={false} 
            //customRequest={handleUpload}
            >
              {/*  */}
              <div
                // className={
                //   formRef.current && formRef.current.getFieldValue().cover
                //     ? style.dis
                //     : style.divDra
                // }
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">
                  点击选择文件或将文件拖拽到此处
                </p>
                <p className="ant-upload-hint">
                  文件将上传到 OSS, 如未配置请先配置
                </p>
              </div>
              <Image
                width={'100%'}
                // className={
                //   formRef.current && formRef.current.getFieldValue().cover
                //     ? style.imgs
                //     : style.dis
                // }
                //src={formRef.current && formRef.current.getFieldValue().cover}
                alt=""
              />
            </Dragger>
          </Form.Item>
          <Form.Item name="cover" label="路径" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Button onClick={showDrawer2}>选择文件</Button>
        </Form>
      </Drawer>
      <div>
        <ProTable
          actionRef={actionRef}
          rowKey={'id'}
          columns={columns}
          cardBordered
          search={false}
          toolbar={{
            settings: [],
          }}
          editable={{
            type: 'multiple',
          }}
          pagination={{
            pageSize: 12,
            current: 1,
          }}
          request={async (options) => {
            options = {
              ...options,
              page: options.current
            }
            delete options.current;
            const { data } = await runAsync(options)
            return {
              data: data[0],
              success: true,
              total: data[1]
            }

          }}
          dateFormatter="string"
          toolBarRender={() => [
            <Button key="3" type="primary">
              {/* <PlusOutlined /> */}
              新建
            </Button>,
          ]}
        ></ProTable>
      </div>
    </div>
  )
}
